<template>
  <div class="builder">
    <div class="container">
      <h1>装机配置</h1>
      <p>选择你想要的电脑配件，我们会帮你检查兼容性并计算总价</p>
      
      <!-- 配置进度 -->
      <div class="build-progress">
        <div class="progress-steps">
          <div class="step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
            <span class="step-number">1</span>
            <span class="step-text">基础配件</span>
          </div>
          <div class="step-divider"></div>
          <div class="step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
            <span class="step-number">2</span>
            <span class="step-text">扩展配件</span>
          </div>
          <div class="step-divider"></div>
          <div class="step" :class="{ active: currentStep >= 3, completed: currentStep > 3 }">
            <span class="step-number">3</span>
            <span class="step-text">兼容性检查</span>
          </div>
          <div class="step-divider"></div>
          <div class="step" :class="{ active: currentStep >= 4 }">
            <span class="step-number">4</span>
            <span class="step-text">完成配置</span>
          </div>
        </div>
      </div>

      <!-- 步骤内容 -->
      <div class="step-content">
        <!-- 步骤1：基础配件 -->
        <div v-if="currentStep === 1" class="step-1">
          <h2>选择基础配件</h2>
          <div class="components-row">
            <div class="component-selector">
              <h3>CPU</h3>
              <select v-model="selectedCpuId" @change="onComponentChange">
                <option value="">请选择CPU</option>
                <option v-for="cpu in cpus" :key="cpu.id" :value="cpu.id">
                  {{ cpu.name }} - ¥{{ cpu.price.toLocaleString() }}
                </option>
              </select>
            </div>
            
            <div class="component-selector">
              <h3>主板</h3>
              <select v-model="selectedMotherboardId" @change="onComponentChange">
                <option value="">请选择主板</option>
                <option v-for="mb in compatibleMotherboards" :key="mb.id" :value="mb.id">
                  {{ mb.name }} - ¥{{ mb.price.toLocaleString() }}
                </option>
              </select>
            </div>
            
            <div class="component-selector">
              <h3>显卡</h3>
              <select v-model="selectedGpuId" @change="onComponentChange">
                <option value="">请选择显卡</option>
                <option v-for="gpu in gpus" :key="gpu.id" :value="gpu.id">
                  {{ gpu.name }} - ¥{{ gpu.price.toLocaleString() }}
                </option>
              </select>
            </div>
          </div>
        </div>

        <!-- 步骤2：扩展配件 -->
        <div v-if="currentStep === 2" class="step-2">
          <h2>选择扩展配件</h2>
          <div class="components-row">
            <div class="component-selector">
              <h3>内存</h3>
              <select v-model="selectedRamId" @change="onComponentChange">
                <option value="">请选择内存</option>
                <option v-for="ram in compatibleRams" :key="ram.id" :value="ram.id">
                  {{ ram.name }} - ¥{{ ram.price.toLocaleString() }}
                </option>
              </select>
            </div>
            
            <div class="component-selector">
              <h3>存储</h3>
              <select v-model="selectedStorageId" @change="onComponentChange">
                <option value="">请选择存储设备</option>
                <option v-for="storage in storages" :key="storage.id" :value="storage.id">
                  {{ storage.name }} - ¥{{ storage.price.toLocaleString() }}
                </option>
              </select>
            </div>
            
            <div class="component-selector">
              <h3>CPU散热器</h3>
              <select v-model="selectedCpuCoolerId" @change="onComponentChange">
                <option value="">请选择CPU散热器</option>
                <option v-for="cooler in compatibleCpuCoolers" :key="cooler.id" :value="cooler.id">
                  {{ cooler.name }} - ¥{{ cooler.price.toLocaleString() }}
                </option>
              </select>
            </div>
          </div>
          
          <div class="components-row">
            <div class="component-selector">
              <h3>电源</h3>
              <select v-model="selectedPowerSupplyId" @change="onComponentChange">
                <option value="">请选择电源</option>
                <option v-for="psu in powerSupplies" :key="psu.id" :value="psu.id">
                  {{ psu.name }} - ¥{{ psu.price.toLocaleString() }}
                </option>
              </select>
            </div>
            
            <div class="component-selector">
              <h3>机箱</h3>
              <select v-model="selectedCaseId" @change="onComponentChange">
                <option value="">请选择机箱</option>
                <option v-for="pcCase in pcCases" :key="pcCase.id" :value="pcCase.id">
                  {{ pcCase.name }} - ¥{{ pcCase.price.toLocaleString() }}
                </option>
              </select>
            </div>
          </div>
        </div>

        <!-- 步骤3：兼容性检查 -->
        <div v-if="currentStep === 3" class="step-3">
          <h2>兼容性检查结果</h2>
          
          <!-- 已选配件列表 -->
          <div class="selected-components">
              <h3>已选配件</h3>
              <div class="components-list">
                <div v-for="item in Object.entries(build)" :key="item[0]">
                  <template v-if="item[1]">
                    <span class="component-type">{{ getComponentTypeName(item[0]) }}</span>
                    <span class="component-name">{{ item[1].name }}</span>
                    <span class="component-price">¥{{ item[1].price.toLocaleString() }}</span>
                  </template>
                </div>
              </div>
            </div>

          <!-- 兼容性结果 -->
          <div class="compatibility-result" :class="{ compatible: compatibilityResult.isCompatible }">
            <div class="result-header">
              <div class="result-icon">
                <svg v-if="compatibilityResult.isCompatible" width="32" height="32" viewBox="0 0 24 24" fill="#4CAF50" stroke="#4CAF50" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                  <polyline points="22 4 12 14.01 9 11.01"></polyline>
                </svg>
                <svg v-else width="32" height="32" viewBox="0 0 24 24" fill="#f44336" stroke="#f44336" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <circle cx="12" cy="12" r="10"></circle>
                  <line x1="15" y1="9" x2="9" y2="15"></line>
                  <line x1="9" y1="9" x2="15" y2="15"></line>
                </svg>
              </div>
              <div class="result-title">
                <h3 v-if="compatibilityResult.isCompatible">🎉 配置兼容！</h3>
                <h3 v-else>⚠️ 配置存在不兼容问题</h3>
              </div>
            </div>
            
            <div v-if="!compatibilityResult.isCompatible" class="incompatibility-reasons">
              <h4>不兼容原因：</h4>
              <ul>
                <li v-for="(reason, index) in compatibilityResult.incompatibilityReasons" :key="index">
                  {{ reason }}
                </li>
              </ul>
            </div>
          </div>

          <!-- 价格汇总 -->
          <div class="price-summary">
            <div class="summary-item">
              <span>配件总价：</span>
              <span v-if="isActiveVip">
                <span class="vip-price">¥{{ totalPrice.toLocaleString() }}</span>
                <span class="original-price">¥{{ originalTotalPrice.toLocaleString() }}</span>
                <span class="savings">省¥{{ savings.toLocaleString() }}</span>
              </span>
              <span v-else class="price">¥{{ totalPrice.toLocaleString() }}</span>
            </div>
            <div class="summary-item">
              <span>性能评分：</span>
              <span class="score">{{ performanceScore }}</span>
            </div>
            <div class="summary-item">
                <span>性价比：</span>
                <span class="value">{{ numberFormat(performanceScore / totalPrice * 1000) }}</span>
              </div>
          </div>
        </div>

        <!-- 步骤4：完成配置 -->
        <div v-if="currentStep === 4" class="step-4">
          <h2>配置完成！</h2>
          
          <div class="build-summary">
                <h3>您的电脑配置</h3>
                <div class="components-list">
                  <div v-for="item in Object.entries(build)" :key="item[0]">
                    <template v-if="item[1]">
                      <span class="component-type">{{ getComponentTypeName(item[0]) }}</span>
                      <span class="component-name">{{ item[1].name }}</span>
                      <span class="component-price">¥{{ item[1].price.toLocaleString() }}</span>
                    </template>
                  </div>
                </div>
            
            <div class="total-price">
              <span>总计：</span>
              <span v-if="isActiveVip">
                <span class="vip-price">¥{{ totalPrice.toLocaleString() }}</span>
                <span class="original-price">¥{{ originalTotalPrice.toLocaleString() }}</span>
                <span class="savings">省¥{{ savings.toLocaleString() }}</span>
              </span>
              <span v-else class="price">¥{{ totalPrice.toLocaleString() }}</span>
            </div>
          </div>

          <div class="action-buttons">
            <button class="btn-primary">保存配置</button>
            <button class="btn-secondary">分享配置</button>
            <button class="btn-secondary">生成清单</button>
          </div>
        </div>
      </div>

      <!-- 导航按钮 -->
      <div class="navigation-buttons">
        <button v-if="currentStep > 1" class="btn-secondary" @click="prevStep">上一步</button>
        <button v-if="currentStep < 4" class="btn-primary" @click="nextStep">下一步</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import type { PCBuild, CompatibilityResult } from '../types/components';
import type { User, VipInfo } from '../types/vip';
import { 
  cpus, gpus, rams, motherboards, storages, 
  powerSupplies, pcCases, cpuCoolers 
} from '../data/mockData';
import { compatibilityChecker } from '../utils/compatibilityChecker';
import { getUserWithVipInfo, isVipActive, calculateVipPrice } from '../utils/vipService';

// 当前步骤
const currentStep = ref<number>(1);

// 选中的配件ID
const selectedCpuId = ref<string>('');
const selectedGpuId = ref<string>('');
const selectedRamId = ref<string>('');
const selectedMotherboardId = ref<string>('');
const selectedStorageId = ref<string>('');
const selectedPowerSupplyId = ref<string>('');
const selectedCaseId = ref<string>('');
const selectedCpuCoolerId = ref<string>('');

// 当前配置
const build = ref<PCBuild>({});

// 兼容性结果
const compatibilityResult = ref<CompatibilityResult>({
  isCompatible: true,
  incompatibilityReasons: []
});

// 用户信息
const user = ref<User | null>(null);

// 加载用户信息
const loadUserInfo = () => {
  user.value = getUserWithVipInfo();
};

// 检查是否为活跃VIP用户
const isActiveVip = computed(() => {
  return isVipActive(user.value?.vipInfo);
});

// 计算原价
const originalTotalPrice = computed(() => {
  let total = 0;
  
  if (build.value.cpu) total += build.value.cpu.price;
  if (build.value.gpu) total += build.value.gpu.price;
  if (build.value.ram) total += build.value.ram.price;
  if (build.value.motherboard) total += build.value.motherboard.price;
  if (build.value.storage) total += build.value.storage.price;
  if (build.value.powerSupply) total += build.value.powerSupply.price;
  if (build.value.pcCase) total += build.value.pcCase.price;
  if (build.value.cpuCooler) total += build.value.cpuCooler.price;
  
  return total;
});

// 计算VIP折扣价
const totalPrice = computed(() => {
  if (!isActiveVip.value) {
    return originalTotalPrice.value;
  }
  
  return calculateVipPrice(originalTotalPrice.value, user.value?.vipInfo, true); // true表示整机折扣
});

// 计算节省金额
const savings = computed(() => {
  if (!isActiveVip.value) {
    return 0;
  }
  
  return originalTotalPrice.value - totalPrice.value;
})

// 生命周期钩子
onMounted(() => {
  loadUserInfo();
  
  // 监听localStorage变化
  window.addEventListener('storage', (event) => {
    if (event.key === 'user' || event.key === 'vipInfo') {
      loadUserInfo();
    }
  });
});

// 计算性能评分
const performanceScore = computed(() => {
  let score = 0;
  let count = 0;
  
  if (build.value.cpu) { score += build.value.cpu.performanceScore; count++; }
  if (build.value.gpu) { score += build.value.gpu.performanceScore; count++; }
  if (build.value.ram) { score += build.value.ram.performanceScore; count++; }
  if (build.value.motherboard) { score += build.value.motherboard.performanceScore; count++; }
  if (build.value.storage) { score += build.value.storage.performanceScore; count++; }
  if (build.value.powerSupply) { score += build.value.powerSupply.performanceScore; count++; }
  if (build.value.pcCase) { score += build.value.pcCase.performanceScore; count++; }
  if (build.value.cpuCooler) { score += build.value.cpuCooler.performanceScore; count++; }
  
  return count > 0 ? Math.round(score / count) : 0;
});

// 获取兼容的主板列表
const compatibleMotherboards = computed(() => {
  if (!selectedCpuId.value) return motherboards;
  const selectedCpu = cpus.find(cpu => cpu.id === selectedCpuId.value);
  if (!selectedCpu) return motherboards;
  return motherboards.filter(mb => mb.socketType === selectedCpu.socketType);
});

// 获取兼容的内存列表
const compatibleRams = computed(() => {
  if (!selectedMotherboardId.value) return rams;
  const selectedMotherboard = motherboards.find(mb => mb.id === selectedMotherboardId.value);
  if (!selectedMotherboard) return rams;
  return rams.filter(ram => ram.type === selectedMotherboard.memoryType);
});

// 获取兼容的CPU散热器列表
const compatibleCpuCoolers = computed(() => {
  if (!selectedCpuId.value) return cpuCoolers;
  const selectedCpu = cpus.find(cpu => cpu.id === selectedCpuId.value);
  if (!selectedCpu) return cpuCoolers;
  return cpuCoolers.filter(cooler => cooler.compatibility.includes(selectedCpu.socketType));
});

// 配件类型名称映射
const getComponentTypeName = (type: string): string => {
  const typeNames: Record<string, string> = {
    cpu: 'CPU',
    gpu: '显卡',
    ram: '内存',
    motherboard: '主板',
    storage: '存储',
    powerSupply: '电源',
    pcCase: '机箱',
    cpuCooler: 'CPU散热器'
  };
  return typeNames[type] || type;
};

// 更新配置
const updateBuild = () => {
  // 根据选中的ID更新配置
  build.value.cpu = selectedCpuId.value ? cpus.find(cpu => cpu.id === selectedCpuId.value) : undefined;
  build.value.gpu = selectedGpuId.value ? gpus.find(gpu => gpu.id === selectedGpuId.value) : undefined;
  build.value.ram = selectedRamId.value ? rams.find(ram => ram.id === selectedRamId.value) : undefined;
  build.value.motherboard = selectedMotherboardId.value ? motherboards.find(mb => mb.id === selectedMotherboardId.value) : undefined;
  build.value.storage = selectedStorageId.value ? storages.find(storage => storage.id === selectedStorageId.value) : undefined;
  build.value.powerSupply = selectedPowerSupplyId.value ? powerSupplies.find(psu => psu.id === selectedPowerSupplyId.value) : undefined;
  build.value.pcCase = selectedCaseId.value ? pcCases.find(pcCase => pcCase.id === selectedCaseId.value) : undefined;
  build.value.cpuCooler = selectedCpuCoolerId.value ? cpuCoolers.find(cooler => cooler.id === selectedCpuCoolerId.value) : undefined;
};

// 检查兼容性
const checkCompatibility = () => {
  compatibilityResult.value = compatibilityChecker.checkCompatibility(build.value);
};

// 配件选择变化时触发
const onComponentChange = () => {
  updateBuild();
  
  // 在第三步时才检查兼容性
  if (currentStep.value === 3) {
    checkCompatibility();
  }
};

// 下一步
const nextStep = () => {
  // 如果是从步骤2到步骤3，先更新配置并检查兼容性
  if (currentStep.value === 2) {
    updateBuild();
    checkCompatibility();
  }
  
  currentStep.value++;
};

// 上一步
const prevStep = () => {
  currentStep.value--;
};

// 格式化数字
const numberFormat = (value: number): string => {
  return value.toFixed(2);
};

// 监听步骤变化
watch(currentStep, (newStep) => {
  // 如果进入第三步，检查兼容性
  if (newStep === 3) {
    updateBuild();
    checkCompatibility();
  }
});

// 将格式化函数添加到全局属性中
import { getCurrentInstance } from 'vue';
const app = getCurrentInstance();
if (app) {
  app.appContext.config.globalProperties.$filters = {
    numberFormat
  };
}
</script>

<style scoped>
.builder {
  padding: 3rem 0;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1.5rem;
}

.builder h1 {
  text-align: center;
  font-size: 2.5rem;
  margin: 0 0 0.5rem 0;
  color: #1a1a1a;
}

.builder p {
  text-align: center;
  color: #666;
  margin: 0 0 3rem 0;
  font-size: 1.1rem;
}

/* 进度条 */
.build-progress {
  margin-bottom: 3rem;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.progress-steps::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #ddd;
  z-index: 1;
  transform: translateY(-50%);
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #ddd;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
  transition: all 0.3s ease;
}

.step-text {
  font-size: 0.9rem;
  color: #666;
  text-align: center;
}

.step.active .step-number {
  background-color: #00ccff;
  color: white;
}

.step.active .step-text {
  color: #00ccff;
  font-weight: bold;
}

.step.completed .step-number {
  background-color: #4CAF50;
  color: white;
}

.step.completed .step-text {
  color: #4CAF50;
  font-weight: bold;
}

.step-divider {
  flex: 1;
}

/* 步骤内容 */
.step-content {
  background-color: white;
  border-radius: 10px;
  padding: 2rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.step-content h2 {
  margin: 0 0 2rem 0;
  color: #1a1a1a;
  font-size: 1.8rem;
}

/* 配件选择器 */
.components-row {
  display: flex;
  gap: 2rem;
  margin-bottom: 2rem;
  flex-wrap: wrap;
}

.component-selector {
  flex: 1;
  min-width: 250px;
}

.component-selector h3 {
  margin: 0 0 0.5rem 0;
  color: #1a1a1a;
  font-size: 1.1rem;
}

.component-selector select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  background-color: white;
  cursor: pointer;
}

/* 已选配件列表 */
.selected-components {
  margin-bottom: 2rem;
}

.selected-components h3 {
  margin: 0 0 1rem 0;
  color: #1a1a1a;
  font-size: 1.3rem;
}

.components-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.components-list > div {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.component-type {
  background-color: #00ccff;
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
  margin-right: 1rem;
  min-width: 80px;
  text-align: center;
}

.component-name {
  flex: 1;
  color: #1a1a1a;
}

.component-price {
  font-weight: bold;
  color: #1a1a1a;
  margin-left: 1rem;
}

/* 兼容性结果 */
.compatibility-result {
  padding: 1.5rem;
  border-radius: 8px;
  margin-bottom: 2rem;
  border: 2px solid #f44336;
  background-color: #ffebee;
}

.compatibility-result.compatible {
  border-color: #4CAF50;
  background-color: #e8f5e9;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.result-title h3 {
  margin: 0;
  color: #1a1a1a;
  font-size: 1.3rem;
}

.incompatibility-reasons h4 {
  margin: 0 0 0.5rem 0;
  color: #f44336;
  font-size: 1.1rem;
}

.incompatibility-reasons ul {
  margin: 0;
  padding-left: 1.5rem;
}

.incompatibility-reasons li {
  color: #333;
  margin-bottom: 0.25rem;
}

/* 价格汇总 */
.price-summary {
  padding: 1.5rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.1rem;
}

.summary-item span:first-child {
  color: #666;
}

.price, .score, .value {
  font-weight: bold;
  color: #1a1a1a;
}

/* VIP价格显示 */
.vip-price {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 1.3rem;
  margin-right: 0.5rem;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 0.9rem;
  margin-right: 0.5rem;
}

.savings {
  color: #52c41a;
  font-size: 0.9rem;
  font-weight: bold;
}

/* 配置汇总 */
.build-summary {
  margin-bottom: 2rem;
}

.build-summary h3 {
  margin: 0 0 1rem 0;
  color: #1a1a1a;
  font-size: 1.3rem;
}

.total-price {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 2px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.5rem;
}

.total-price .price {
  color: #00ccff;
  font-size: 2rem;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

/* 导航按钮 */
.navigation-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

/* 按钮样式 */
.btn-primary, .btn-secondary {
  padding: 1rem 2rem;
  border: none;
  border-radius: 4px;
  font-size: 1.1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  display: inline-block;
  text-align: center;
}

.btn-primary {
  background-color: #00ccff;
  color: #1a1a1a;
}

.btn-primary:hover {
  background-color: #00a3cc;
  transform: translateY(-2px);
}

.btn-secondary {
  background-color: transparent;
  color: #00ccff;
  border: 2px solid #00ccff;
}

.btn-secondary:hover {
  background-color: #00ccff;
  color: #1a1a1a;
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .builder h1 {
    font-size: 2rem;
  }
  
  .progress-steps {
    flex-direction: column;
    gap: 1rem;
  }
  
  .progress-steps::before {
    top: 0;
    left: 50%;
    bottom: 0;
    right: auto;
    width: 2px;
    height: calc(100% - 60px);
    transform: translateX(-50%);
  }
  
  .step-divider {
    display: none;
  }
  
  .components-row {
    flex-direction: column;
  }
  
  .component-selector {
    width: 100%;
  }
  
  .navigation-buttons {
    justify-content: center;
    flex-direction: column;
    gap: 1rem;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .btn-primary, .btn-secondary {
    width: 100%;
  }
}
</style>